﻿/// <reference path="../jquery-1.9.1.min.js" />
/**
* Html5 Audio
* 用户按钮操作 音效逻辑封装
*/
(function (window, $) {
    function AudioCtrl(opts) {
        var js = document.scripts;
        js = js[js.length - 1].src.substring(0, js[js.length - 1].src.lastIndexOf("/") + 1);
        this.folder = js;
        //默认参数定义
        var defaults = {
            url: this.folder + '/glass.mp3',//歌曲地址
            volume: 100,//当前声音大小
            autoPlay: false,//是否自动播放
            loop: false,//是否循环播放
            type: 1,//控件样式类型，1-一般样式 2-简易样式 
            canFold: true,//指定简易模式下是否可折叠
            onPlay: function (audio) { },//当开始播放
            onEnded: function (audio) { },//当播放结束
        }
        this.opts = $.extend({}, defaults, opts);
        this.init();
    }
    AudioCtrl.prototype = {
        //初始化
        init: function () {
            var _this = this;
            var _opts = this.opts;
            //根据类型初始化
            _this.initSimple();
        },
        //初始换简单样式
        initSimple: function () {
            var _this = this;
            var _opts = this.opts;
            //绑定Audio标签
            var audio = $('<audio />');
            var _audio = this.audio = audio.get(0);
            audio.attr('src', _opts.url);
            audio.volume = _opts.volume;
            audio.loop = _opts.loop;
            $(document.body).append(audio);
            _audio.onplay = function () {
                if (_opts.onPlay)
                    _opts.onPlay(_audio);
            }
            //播放结束
            _audio.onended = function () {
                pauseHandle();
                if (_opts.onEnded)
                    _opts.onEnded(_audio);
            }
            if (_opts.autoPlay) {
                playHandle();
            }
            //播放处理
            function playHandle() {
                //播放样式
                //播放
                _this.play();
            }
            //暂停处理
            function pauseHandle() {
                //暂定样式
                //暂停
                _this.pause();
            }
        },
        //播放
        play: function () {
            var _this = this;
            var audio = _this.audio;
            audio.play();
        },
        //暂停
        pause: function () {
            var _this = this;
            var audio = _this.audio;
            audio.pause();
        },
        //销毁控件
        destroy: function () {
            var _this = this;
            _this.pause();
            _this.elem.remove();
        }
    }
    //获取div
    function getDivByClass(cla) {
        var div = $('<div />');
        div.addClass(cla);
        return div;
    }
    window.AudioCtrl = AudioCtrl;
    window.audio = new AudioCtrl();
})(window, jQuery);

